package com.example.tabbar.fragment


import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.Switch
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.tabbar.R
import com.example.tabbar.databinding.FragmentSetShowBinding
import com.example.tabbar.utils.BrightnessUtils
import com.example.tabbar.utils.CustomSpinner


class SetShowFragment : Fragment() {
    private var binding: FragmentSetShowBinding? = null
    private var seekbar: SeekBar? = null
    private var selectTimeFormatter: TextView? = null
    private val brightnessUtils = BrightnessUtils()
    private var setVoice: Switch? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentSetShowBinding.inflate(inflater, container, false)
        return binding!!.root
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setVoice = binding?.voice
        selectTimeFormatter = binding?.selectTimeFormatter
        initSeekBar()

        initSeekBarProgress()
        setTimeSpinner()

        onClick()
        //获取当前页面的宽度
        // 方法2：在视图布局完成后获取
        view.post {
            val fragmentWidth = view.width
            val measuredWidth = view.measuredWidth
            Log.d("width", "width: $fragmentWidth measuredWidth: $measuredWidth")
        }

    }

    private fun onClick() {
        // 点击整行设置switch开关
        binding?.setVoice?.setOnClickListener {
            setVoice?.isChecked = !setVoice?.isChecked!!
        }
    }

    //现实不能跳转，所以默认就要有权限
//    private fun requestWriteSettingsPermission() {
//        val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
//        intent.data = Uri.parse("package:${requireActivity().packageName}")
//        startActivity(intent)
//    }

    private fun initSeekBarProgress() {
        if (brightnessUtils.hasWriteSettingsPermission(requireContext())) {
            try {
                // 获取当前系统亮度
                val currentBrightness = brightnessUtils.getSystemBrightness(requireContext())
                // 转换为百分比进度
                val progress = brightnessUtils.systemValueToPercentage(currentBrightness)
                // 设置SeekBar初始进度
                binding?.seekbar?.progress = progress
            } catch (e: Exception) {
                Log.e("Brightness", "设置初始进度失败", e)
            }
        }
    }
    private fun initSeekBar() {
        seekbar = binding?.seekbar

        seekbar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                //3588屏幕配合api使用可以直接设置亮度
//                SdkApi.getInstance().Display().setBrightness(ApiTool.Screen.MIPI, progress)

                // 其他设备设置屏幕亮度
                if(brightnessUtils.hasWriteSettingsPermission(requireContext())) {
                    setScreenManualMode()
                    try {
                        val brightness = brightnessUtils.percentageToSystemValue(progress)
                        Settings.System.putInt(
                            requireActivity().contentResolver,
                            Settings.System.SCREEN_BRIGHTNESS,
                            brightness
                        )
                    } catch (e: Exception) {
                        Log.e("Brightness", "设置亮度失败", e)
                    }
                } else {
                    Log.d("Brightness", "没有权限")
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })
    }

    /**
     * 设置系统亮度调节模式(SCREEN_BRIGHTNESS_MODE)
     * SCREEN_BRIGHTNESS_MODE_MANUAL 手动调节
     * SCREEN_BRIGHTNESS_MODE_AUTOMATIC 自动调节
     */
    private fun setScreenManualMode() {
        try {
            //获取当前系统亮度调节模式
            val mode = Settings.System.getInt(requireActivity().contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)
            //如果是自动，则改为手动
            if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                Settings.System.putInt(
                    requireActivity().contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
                )
            }
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }
    }

    private fun setTimeSpinner() {
        val items = arrayListOf("简体中文", "英文")
        val customSpinner = CustomSpinner(requireContext(), items) { _, item ->
            selectTimeFormatter?.text = item
        }
        customSpinner.setOnDismissListener {
            selectTimeFormatter?.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.to_down, 0)
        }

        val unitSelectedPosition = 0

        customSpinner.setSelectedPosition(unitSelectedPosition)



        selectTimeFormatter?.setOnClickListener {
            selectTimeFormatter?.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.to_up, 0)
            customSpinner.show(selectTimeFormatter!!)
        }
    }


    companion object {

        @JvmStatic
        fun newInstance() =
            SetShowFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
}